/*
 * Copyright 2021 Roberto Leinardi.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.leinardi.android.speeddial;

import android.content.Context;

import android.util.AttributeSet;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.MenuRes;
import androidx.annotation.Nullable;

import androidx.appcompat.widget.PopupMenu;

import com.google.android.material.floatingactionbutton.FloatingActionButton;


@SuppressWarnings({"unused", "WeakerAccess", "UnusedReturnValue"})
public class SpeedDialView extends AbstractSpeedDialView {

    public SpeedDialView(Context context) {
        super(context);
    }

    public SpeedDialView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SpeedDialView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Inflate a menu resource into this SpeedDialView. Any existing Action item will be removed.
     * <p class="note">Using the Menu resource it is possible to specify only the ID, the icon and the label of the
     * Action item. No color customization is available.</p>
     *
     * @param menuRes Menu resource to inflate
     */
    @Override
    public void inflate(@MenuRes int menuRes) {
        clearActionItems();
        PopupMenu popupMenu = new PopupMenu(getContext(), new View(getContext()));
        popupMenu.inflate(menuRes);
        Menu menu = popupMenu.getMenu();
        SpeedDialActionItem actionItem;
        MenuItem menuItem;
        int defaultColor;
        for (int i = 0; i < menu.size(); i++) {
             menuItem = menu.getItem(i);
            if(isSpeedDialFabBackgroundColorRandom)
                defaultColor = UiUtils.randomColor();
            else
                defaultColor = speedDialDefaultBackgroudColor;
             actionItem = new SpeedDialActionItem.Builder(menuItem.getItemId(), menuItem.getIcon())
                    .setLabel(menuItem.getTitle() != null ? menuItem.getTitle().toString() : null)
                     .setFabBackgroundColor(defaultColor)
                    .create();
            addActionItem(actionItem);
        }
    }

    @Override
    protected void initMainFabWithClickListener(FloatingActionButton fab) {
        mSpeedDialFab=fab;
        addSpeedDialFabClickListener(mSpeedDialFab);
    }

}
